package com.example.redisdemo.controller;

import com.example.redisdemo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Set;

@RestController
public class RedisController {

    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("/test")
    public String test() {
        return "test.";
    }

    @RequestMapping("/string")
    public String stringTest() {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        valueOperations.set("hello", "hello");
        valueOperations.set("redis", "redis");
        valueOperations.set("!", "!");
        return (String) valueOperations.get("hello");
    }

    @RequestMapping("/object")
    public User objectTest(@RequestBody User user) {
        ValueOperations<String, User> valueOperations = redisTemplate.opsForValue();
        valueOperations.set("objectkey", user);
        return valueOperations.get("objectkey");
    }

    @RequestMapping("/set")
    public Set<String> setTest() {
        SetOperations<String, String> setOperations = redisTemplate.opsForSet();
        setOperations.add("setkey", "hello");
        setOperations.add("setkey", "redis");
        setOperations.add("setkey", "!");
        return setOperations.members("setkey");
    }

    @RequestMapping("/zset")
    public Set<String> zsetTest() {
        ZSetOperations<String, String> zSetOperations = redisTemplate.opsForZSet();
        zSetOperations.add("zsetkey", "hello", 1);
        zSetOperations.add("zsetkey", "redis", 2);
        zSetOperations.add("zsetkey", "!", 3);
        return zSetOperations.range("zsetkey", 0, 2);
    }

    @RequestMapping("/list")
    public List<String> listTest() {
        ListOperations<String, String> listOperations = redisTemplate.opsForList();
        listOperations.leftPush("listkey", "hello");
        listOperations.leftPush("listkey", "redis");
        listOperations.leftPush("listkey", "!");
        return listOperations.range("listkey", 0, 2);
    }

    @RequestMapping("/hashmap")
    public HashMap<String, String> hashmapTest() {
        HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();
        hashOperations.put("key", "hashkey", "hello");
        hashOperations.put("key", "hashkey", "redis");
        hashOperations.put("key", "hashkey2", "!");
        return (HashMap<String, String>) hashOperations.entries("key");
    }

}
